
// Hack to determine some code paths
server = true;

// Don't calculate implicit state every frame
// UPDATE: That's not what this turned out to mean...
doUpdateEntities = true;

// Imports aren't "modules" and end up in global namespace

require('../shared/state');
require('../shared/model');
require('../shared/entmodels');
require('../shared/physics'); // Time, step()
var HeightMap = require('../shared/heightmap');
require('./network');
var Player = require('./player');


ServerGame = function(state, groundMap, time) {
    this.state = state;
    this.groundMap = groundMap;
    this.time = time;
};

var state = new State();

var heightmap = new new HeightMap(400 * 7, 32 * 7);

var game = new ServerGame(state, heightmap, new Time());

var players = [];

// Toying around
hasPlayer = false;

var network = new NetworkManager({
    time: game.time
});

network.on('player_connected', function(clientInfo) {
    console.log('conn:' + clientInfo.id);
    var c = Car(2.5, 7.5, 5, clientInfo.id);
    var p = new Player(clientInfo.id, c, clientInfo.socket, game.time.getFrameId());
    //state.empty();
    var pid = state.add(c);
    //players = [p];
    players.push(p);
});

network.on('player_disconnected', function(clientInfo) {
    var id = clientInfo.id, i, found = false;
    for (i = players.length - 1; i > -1; --i) {
	if (players[i]) {
	    found = true;
	    game.state.remove(players[i].car);
	    break;
	}
    }
    if (found)
	players.splice(i, 1);
});

var frameTime = Date.now();
var lf = 0;
function gameloop() {
    
    var i, n = players.length, t=0;
    var msg;
    while (game.time.hasTick()) {
	t = game.time.getFrameId();
	for (i = 0; i < n; ++i) {
	    players[i].addStateBufferEntry(t);
	}
	step(game, game.time.getTick());
	if (players.length ) {
	    t = game.time.getFrameId();
	}
    }

    for (i = 0; i < n; ++i) {
	players[i].applyCommands(game);
    }

    var now = Date.now();
    if (now - frameTime >= 500) {
	msg = JSON.stringify({
            frameId: game.time.getFrameId(),
            t: now,
            m: 'st',
            state: game.state.serialize()
        });
	
	// That's right. Very, very poor man's latency faking...
	setTimeout(function() {
	    network.broadcast(msg);
	}, 80);
        
        frameTime = now;
    }
    
}
setInterval(gameloop, 1000 / 60);

console.log('Running');